<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input style="width: 200px;" class="filter-item" placeholder="名称" v-model="listQuery.roleName">
      </el-input>
      <el-input style="width: 200px;" class="filter-item" placeholder="备注" v-model="listQuery.remark">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh" @click="restQuery">{{$t('table.reset')}}</el-button>

      <el-button v-has="'sysRole_add'" class="filter-item" @click="handleCreate" type="primary" icon="el-icon-plus">新增角色</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" :label="$t('table.id')" width="65">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.roleName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注">
        <template slot-scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.actions')" width="360" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-has="'sysRole_edit'" type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button v-has="'sysRole_info'" type="info" size="mini" @click="handleInfo(scope.row,'info')">{{$t('table.info')}}</el-button>
          <el-button v-has="'sysRole_auth'" type="info" size="mini" @click="handleRoleInfo(scope.row)">权限</el-button>
          <el-button v-has="'sysRole_delete'" size="mini" type="danger" @click="handleDelete(scope.row,'deleted')">{{$t('table.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @current-change="handleCurrentChange" :current-page="page.page" :page-size="page.limit" layout="total, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="名称" prop="roleName">
          <span v-if="dialogStatus=='info'">{{temp.roleName}}</span>
          <el-input v-else v-model="temp.roleName"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <span v-if="dialogStatus=='info'">{{temp.remark}}</span>
          <el-input v-else type="textarea" v-model="temp.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="dialogStatus !== 'info'">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogRoleTreeVisible" width="20%" title="角色权限树">
      <el-tree :data="data" show-checkbox default-expand-all node-key="id" ref="roleTree" highlight-current :props="defaultProps" :default-checked-keys="defaultCheckArray">
      </el-tree>
      <div slot="footer" class="dialog-footer" v-if="dialogStatus !== 'info'">
        <el-button @click="dialogRoleTreeVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="updateRoleData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  fetchSysRole,
  infoSysRole,
  createSysRole,
  deleteSysRole,
  updateSysRole,
  fetchMenuList
} from '@/api/user/sysRole'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'

export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      page: {
        page: 1,
        limit: 20,
        sort: ''
      },
      listQuery: {
        roleName: undefined,
        routerNameGroup: undefined,
        authCodeGroup: undefined,
        remark: undefined
      },
      dialogFormVisible: false,
      dialogRoleTreeVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增',
        info: '详情'
      },
      temp: {
        roleName: '',
        routerNameGroup: '',
        authCodeGroup: '',
        remark: ''
      },
      defaultCheckArray: [],
      rules: {
        roleName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
      },
      data: []
    }
  },
  filters: {},
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchSysRole(this.listQuery).then(response => {
        this.list = response.content.list
        this.total = response.content.total
        this.listLoading = false
      })
    },
    // 搜索按钮
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 跳转页数
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 详情
    handleInfo(row, status) {
      infoSysRole(row.id).then(response => {
        if (response.success) {
          this.temp = Object.assign({}, response.content) // copy obj
          this.dialogStatus = status
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
      })
    },
    // 角色权限详情
    handleRoleInfo(row) {
      var p = { parentId: '0' }
      fetchMenuList(p).then(response => {
        if (response.success) {
          this.data = Object.assign([], response.content) // copy obj
          this.dialogRoleTreeVisible = true
        }
      })
      infoSysRole(row.id).then(response => {
        if (response.success) {
          this.temp = Object.assign({}, response.content) // copy obj
          this.defaultCheckArray = response.content.routerNameGroup.split('#')
        }
      })
    },
    resetTemp() {
      this.temp = {
        roleName: '',
        routerNameGroup: '',
        authCodeGroup: '',
        remark: ''
      }
    },
    // 打开新增dialog
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增数据post
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createSysRole(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 更新页面
    handleUpdate(row) {
      infoSysRole(row.id).then(response => {
        this.temp = Object.assign({}, response.content) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    // 提交更新
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateSysRole(tempData).then(response => {
            if (response.success) {
              this.dialogFormVisible = false
              this.dialogRoleTreeVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    // 删除操作
    handleDelete(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 调用删除接口
          var p = { id: row.id }
          deleteSysRole(p).then(response => {
            if (response.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    updateRoleData() {
      var treedata = this.$refs.roleTree.getCheckedKeys()
      this.temp.routerNameGroup = treedata.join('#')
      const tempData = Object.assign({}, this.temp)
      updateSysRole(tempData).then(response => {
        if (response.success) {
          this.dialogFormVisible = false
          this.dialogRoleTreeVisible = false
          this.getList()
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    restQuery() {
      this.listQuery.roleName = ''
      this.listQuery.remark = ''
      this.getList()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" slot-scoped>
.el-dialog__body {
  overflow:auto;
  max-height: 500px;
}

</style>
